from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import User,News

'''
@登录
'''
def login(request):
	if(request.method=="POST"):
		username=request.POST["username"]
		passwd=request.POST["passwd"]
		islogin=User.objects.filter(username__exact=username,passwd__exact=passwd)
		if(islogin):
			request.session["userlogin"]=username
			return HttpResponseRedirect("/newslist")
		else:
			return HttpResponse("登录失败")
	return render(request,"login.html")

'''
@注册
'''
def register(request):
	if(request.method=='POST'):
		username = request.POST["username"]
		passwd = request.POST["passwd"]
		phone=request.POST["phone"]
		email=request.POST["email"]
		isadmin=False
		User.objects.create(username=username,passwd=passwd,phone=phone,email=email,isadmin=isadmin,)
		request.session["userlogin"] = username
		return HttpResponseRedirect("/newslist")
	return render(request,"register.html")

'''
@新闻列表主页
'''
def newslist(request):
	if request.session.has_key("userlogin"):
		username=request.session["userlogin"]
		a="退出"
		b="/logout"
		article=News.objects.all().values('id','title','author','newstypename','content')
		return render(request,"news.htm",{"username":username,"a":a,"b":b,
										  "article":article,})
	else:
		a="请登录"
		b="/login"
		article = News.objects.all().values('id', 'title', 'author', 'newstypename', 'content')
		return render(request, "news.htm", {"a": a, "b": b,
										"article": article, })
'''
@退出
'''
def logout(request):
	del request.session["userlogin"]
	return HttpResponseRedirect("/newslist")
'''
@发布新闻页
'''
def release(request):
	if request.session.has_key("userlogin"):
		username=request.session["userlogin"]
		a="退出"
		b="/logout"
		if(request.method=="POST"):
			title=request.POST["newstitle"]
			author=request.session["userlogin"]
			content=request.POST["content"]
			type=request.POST["type"]
			News.objects.create(title=title,author=author,content=content,newstypename=type)
			return HttpResponseRedirect("/newslist")
		return render(request,"release.html",{"username":username,"a":a,"b":b,})
	else:
		return  HttpResponseRedirect("/login")
'''
@新闻详情页
'''
def newsdetails(request,newsid):
	article=News.objects.get(id=newsid)
	title=article.title
	author=article.author
	type=article.newstypename
	content=article.content
	return render(request,"newsdetails.html",{
									"title":title,
									"author":author,
									"type":type,
									"content":content,})